import time
import json
import webapp2

from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, bankaccount
from common import functions
from wtforms.ext.appengine.db import model_form

from BaseHandler import BaseHandler

class BankAccount(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(BankAccount, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'name': _('Bank name'), 'bank_code': _('Bank code'), 'cashdesk_code': _('Counter code'),
                       'account_num': _('Bank account'), 'RIB_key': _('RIB key'), 'domiciliation': _('Domiciliation'),
                       'comment': _('Comment'), 'IBAN': _('IBAN'), 'BIC': _('BIC'), 'subaccount': _('Account')
                       }
    
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        template_values = {
                           'title': _('Bank accounts. %s' % imm.name),
                           'header': _('%s. Bank accounts.' % imm.name),
                           'app_user': self.au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'creation',
                           'leftmenu': 'bank',
                           'fields': self.fields
                           }

        template = self.jinja2.get_template('templates/bankaccounts_list.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        bank_accounts = imm.bankaccount_set.order('name').run()
        ba = []
        for b in bank_accounts:
            ba.append([unicode(b.name), unicode(b.bank_code), unicode(b.cashdesk_code), b.account_num, b.RIB_key, unicode(b.domiciliation), unicode(b.comment), b.IBAN, b.BIC, str(b.key())])
        ret = {}
        ret['aaData'] = ba
        self.response.out.write(json.dumps(ret))
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        BankAccountForm = model_form(bankaccount, exclude=['immeuble','lastchange_by'])
            
        if self.request.method == 'GET':
            form = BankAccountForm()
            
        if self.request.method == 'POST':
            form = BankAccountForm(self.request.POST)
            
            if form.validate():
                new_ba = bankaccount(lastchange_by = self.au, 
                                     immeuble = imm, 
                                     name = form['name'].data,
                                     bank_code = form['bank_code'].data,
                                     cashdesk_code = form['cashdesk_code'].data,
                                     account_num = form['account_num'].data,
                                     RIB_key = form['RIB_key'].data,
                                     domiciliation = form['domiciliation'].data,
                                     comment = form['comment'].data,
                                     IBAN = form['IBAN'].data,
                                     BIC = form['BIC'].data,
                                     )
                new_ba.put()
                while not new_ba.is_saved():
                    time.sleep(2)
                
                ok_message = _('Bank account was added.')
            
            
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        ba_id = kwargs.get('ba_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return    
        ba_obj = bankaccount.get(ba_id)
        if not ba_obj: 
            self.redirect(webapp2.uri_for('mainpage'))
            return    
            
        ok_message = ''
        BankAccountForm = model_form(bankaccount, exclude=['immeuble','lastchange_by'])
            
        if self.request.method == 'GET':
            form = BankAccountForm(obj = ba_obj)
            
        if self.request.method == 'POST':
            form = BankAccountForm(self.request.POST)
            
            if form.validate():
                form.populate_obj(ba_obj)
                ba_obj.lastchange_by = self.au 
                                     
                ba_obj.put()
                
                ok_message = _('Bank account was saved.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
